package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.PageResult;
import cn.itcast.hotel.pojo.RequestParams;
import cn.itcast.hotel.service.IHotelService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParams params) {
        try {
            //1.准备Resquest
            SearchRequest request = new SearchRequest("hotel");

            //2. 准备DSL
            //2.1 query
            buildBasicQuery(params, request);

            //2.2 分页
            int page = params.getPage();
            int size = params.getSize();
            request.source().from((page-1)*size).size(size);

            //2.3 距离排序
            String location = params.getLocation();
            if (location!=null && !location.equals("")){//"31.03463, 121.61245"

                request.source().sort(SortBuilders.geoDistanceSort(
                        "location",new GeoPoint(location))
                        .order(SortOrder.ASC)
                        .unit(DistanceUnit.KILOMETERS)
                );
            }


            //3. 发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //4. 解析响应
            return handleResponse(response);

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 聚合出 过滤条件 数据，用于放在过滤条件那
     * @return
     */
    @Override
    public Map<String, List<String>> filters(RequestParams params) {
        try {
            //准备请求
            SearchRequest request = new SearchRequest("hotel");

            //准备DSL
            //query
            buildBasicQuery(params, request);
            //设置size
            request.source().size(0);//不输出文档
            //聚合
            buildAggregation(request);

            //发送请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);

            //解析结果-参考控制台那DSL返回的

            Aggregations aggregations = response.getAggregations();

            List<String> brandList = getAggByName("brandAgg", aggregations);
            List<String> cityList = getAggByName("cityAgg", aggregations);
            List<String> starList = getAggByName("starAgg", aggregations);

            Map<String, List<String>> result= new HashMap<>();
            result.put("brand",brandList);
            result.put("city",cityList);
            result.put("starName",starList);

//            System.out.println(result);

            return result;

        } catch (IOException e) {
            throw new RuntimeException(e);//异常转成运行时异常
        }
    }

    /**
     * 搜索自动补全
     * @param prefix
     * @return
     */
    @Override
    public List<String> getSuggestions(String prefix) {

        try {
            SearchRequest request = new SearchRequest("hotel");

            request.source().suggest(new SuggestBuilder().addSuggestion(
                    "hotelSuggestion", SuggestBuilders
                            .completionSuggestion("suggestion")
                            .prefix(prefix)
                            .skipDuplicates(true)
                            .size(10)));

            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            CompletionSuggestion suggestion=response.getSuggest().getSuggestion("hotelSuggestion");
            List<CompletionSuggestion.Entry.Option> options = suggestion.getOptions();
            List<String> list=new ArrayList<>();

            for (CompletionSuggestion.Entry.Option option : options) {
                String s = option.getText().toString();
                list.add(s);
            }
            return list;

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 根据聚合名称，获取聚合结果集合
     * @param aggName
     * @param aggregations
     * @return
     */
    private List<String> getAggByName(String aggName, Aggregations aggregations) {
        Terms brandTerms = aggregations.get(aggName); //直接用聚合类型去接收
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();

        List<String> brandList = new ArrayList<>();

        for (Terms.Bucket bucket : buckets) {
            String key = bucket.getKeyAsString();
//            System.out.println(key);
            brandList.add(key);
        }
        return brandList;
    }

    /**
     * 构建聚合
     * @param request
     */
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("cityAgg")
                .field("city")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("starAgg")
                .field("starName")
                .size(100)
        );
    }

    private void buildBasicQuery(RequestParams params, SearchRequest request) {
        BoolQueryBuilder boolQuery = new BoolQueryBuilder();

        String key = params.getKey();
        String city = params.getCity();
        String brand = params.getBrand();
        String starName = params.getStarName();
        Integer maxPrice = params.getMaxPrice();
        Integer minPrice = params.getMinPrice();

        if (key==null || "".equals(key)){
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        else{
            boolQuery.must(QueryBuilders.matchQuery("all",key));
        }

        //城市条件
        if (city != null && !city.equals("")){
            boolQuery.filter(QueryBuilders.termQuery("city", city));
        }
        //品牌条件
        if (brand!=null && !brand.equals("")){
            boolQuery.filter(QueryBuilders.termQuery("brand",brand));
        }
        //星级条件
        if (starName!=null && !starName.equals("")){
            boolQuery.filter(QueryBuilders.termQuery("starName",starName));
        }
        //价格条件
        if (minPrice!=null && maxPrice!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("price")
                    .gte(minPrice).lte(maxPrice));
        }

        //2.算分控制
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                //原始查询
                boolQuery,
                //function score数组
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        //其中一个function score 元素
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                //过滤条件
                                QueryBuilders.termQuery("isAD",true),
                                //算分函数
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                });

        request.source().query(functionScoreQuery);
    }

    private PageResult handleResponse(SearchResponse response) {

        List<HotelDoc> hotels=new ArrayList<>();

        //解析结果
        SearchHits searchHits = response.getHits();
        long total = searchHits.getTotalHits().value;
        System.out.println("共搜索到数据：" + total + "条");

        SearchHit[] hits = searchHits.getHits();
        for (SearchHit hit : hits) {

            String json = hit.getSourceAsString();
            HotelDoc hotelDoc = JSON.parseObject(json, HotelDoc.class);

            //获取排序值
            Object[] sortValues = hit.getSortValues();
            if (sortValues.length>0){
                Object sortValue = sortValues[0];
                hotelDoc.setDistance(sortValue);
            }

            hotels.add(hotelDoc);

        }

        PageResult pageResult=new PageResult();
        pageResult.setTotal(total);

        pageResult.setHotels(hotels);

        return pageResult;
    }


}
